﻿using Cimbalino.Phone.Toolkit.Services;
using DepSoft.Mobile.WP8.FollwIt.Messages;
using FollwItPortable;
using FollwItPortable.Model;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;

namespace DepSoft.Mobile.WP8.FollwIt.ViewModel
{
    public class MoviesViewModel : AppCreativityViewModelBase
    {
        private IFollwItClient _follwItClient;

        private ObservableCollection<FollwItMovie> _movies = new ObservableCollection<FollwItMovie>();
        public ObservableCollection<FollwItMovie> Movies
        {
            get { return _movies; }
            set
            {
                if (value == _movies)
                    return;

                _movies = value;
                RaisePropertyChanged();
            }
        }

        public MoviesViewModel(IFollwItClient follwItClient, INavigationService navigationService, IMessenger messenger)
            : base(navigationService, messenger)
        {
            _follwItClient = follwItClient;

            messenger.Register<FollwItUserMessage>(this, Tokens.ForMovies, async message => RefreshLayout(message.UserName));
        }

        private async Task RefreshLayout(string userName)
        {
            this.IsBusy = true;

            this.Movies.Clear();
            List<FollwItMovie> movies = new List<FollwItMovie>();
            try
            {
                movies = await Task.Run(() => _follwItClient.GetUserMovieCollectionAsync(userName));
            }
            catch (Exception e)
            {

            }

            foreach (FollwItMovie movie in movies)
                this.Movies.Add(movie);

            this.IsBusy = false;
        }
    }
}
